package com.xuanzheng.company.filter;

import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/normal_home.html", "/manager_home.html", "/admin_home.html"})
public class SessionFilter implements Filter {
    private final CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);
        
        String requestURI = httpRequest.getRequestURI();
        
        // 检查是否已登录
        boolean isLoggedIn = false;
        boolean hasPermission = false;
        
        if (session != null) {
            // 获取用户对象
            Object userObj = session.getAttribute("user");
            if (userObj != null && userObj instanceof User) {
                User user = (User) userObj;
                isLoggedIn = true;
                
                if (requestURI.contains("normal_home.html")) {
                    // 普通用户页面：需要角色为0
                    hasPermission = (user.getRole() == 0);
                } else if (requestURI.contains("manager_home.html")) {
                    // 公司负责人页面：需要角色为1
                    hasPermission = (user.getRole() == 1);
                } else if (requestURI.contains("admin_home.html")) {
                    // 管理员页面：需要角色为2
                    hasPermission = (user.getRole() == 2);
                }
            }
        }

        // 如果已登录并有权限则放行
        if (isLoggedIn && hasPermission) {
            chain.doFilter(request, response);
        } else {
            // 未登录或没有权限，重定向到登录页面
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.html");
        }
    }

    @Override
    public void destroy() {
    }
} 